/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Servlet.user;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import server.process.LimitationException;
import server.process.ProcessBeanLocal;

/**
 *
 * @author Hoang
 */
public class doUpload extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String photoname = null;
        String description = null;
        String tag=null;
        String slCollection=null;
        try {
            if (!ServletFileUpload.isMultipartContent(request)) {
                throw new RuntimeException("Upload failed");
            }
            ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
            List fileItemsList = servletFileUpload.parseRequest(request);
            String optionalFileName = "";
            FileItem fileItem = null;
            Iterator it = fileItemsList.iterator();
            while (it.hasNext()) {
                FileItem fileItemTemp = (FileItem) it.next();
                System.out.println(fileItemTemp.getFieldName());
                if (fileItemTemp.isFormField()) {
                    if (fileItemTemp.getFieldName().equals("txtName")) {
                        photoname = fileItemTemp.getString();
                    } else if (fileItemTemp.getFieldName().equals("txtDescription")) {
                        description = fileItemTemp.getString();
                    } else if (fileItemTemp.getFieldName().equals("tag")) {
                        tag = fileItemTemp.getString();
                    } else if (fileItemTemp.getFieldName().equals("slCollection")) {
                        slCollection = fileItemTemp.getString();
                    }
                } else {
                    fileItem = fileItemTemp;
                }
            }
            if (fileItem == null) {
                //fileupload is empty
            }
            String filename = fileItem.getName();
            //bug for IE
            File fIE = new File(filename);
            if (fIE.isFile()){
                filename=fIE.getName();
            }
            //
            ServletConfig config = getServletConfig();
            String RealPath = config.getServletContext ().getRealPath ("/");
            System.out.println(RealPath);
            String dir = "photoupload"+"/";
            if (fileItem.getSize() > 0) {
                String dirname = RealPath+dir+"\\";
                File saveto = new File(dirname + filename);
                fileItem.write(saveto);
            }
            Context ctx = new InitialContext();
            ProcessBeanLocal local = (ProcessBeanLocal) ctx.lookup("ProcessLocalJNDI");
            HttpSession session = request.getSession();
            try{
            local.insertNewPhoto(photoname, dir+filename, description, tag, session.getAttribute("username").toString(), slCollection);
            }catch (LimitationException le){
                RequestDispatcher rd = request.getRequestDispatcher("upload.jsp");
                request.setAttribute("UploadERR", "Your selected collection is full (limit 35 photo)");
                rd.forward(request, response);
                return;
            }
            RequestDispatcher rd = request.getRequestDispatcher("upload.jsp");
            request.setAttribute("SUCCESS", 1);
            request.setAttribute("imageurl", "photoupload/"+filename);
            request.setAttribute("View link", "http://localhost:8080/Eproject-war/view.jsp?id=");
            request.setAttribute("Download link:", "http://localhost:8080/Eproject-war/download?id=");
            rd.forward(request, response);

        } catch (FileUploadException ex) {
            Logger.getLogger(doUpload.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(doUpload.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
